package com.example.springboot.utils;

import java.io.*;

public class IoUtils {
    private static final String FILE_UPLOAD_PATH = System.getProperty("user.dir") + File.separator + "/RaceFiles/";

    public static boolean writeFile(InputStream in,String outPath,String fileName) throws FileNotFoundException {
        try {
            File uploadFile = new File(FILE_UPLOAD_PATH + fileName);
            File parentFile = uploadFile.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            // 1. 创建一个字节数组作为数据读取的临时区
            byte[] buffer = new byte[1024];
            // 2. 创建一个 BufferedInputStream 缓存输入流对象用于读取文件
            InputStream bis = new BufferedInputStream(in);
            //定义输出流，将文件写入硬盘
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outPath));//速度快
            // 4. 循环读取文件内容到临时区，并将缓冲区中的数据写入到输出文件中
            int length;
            while ((length = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, length);
            }
            bis.close();
            bos.close();
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
}
